package com.icim.util;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class TimeUtil {
	  private static String strMySQLTimeFormat = "yyyy-MM-dd HH:mm:ss";

	  public static String stackTraceToString(Exception excp) { StringWriter sw = new StringWriter();
	    PrintWriter pw = new PrintWriter(sw, true);
	    excp.printStackTrace(pw);
	    pw.flush();
	    sw.flush();
	    return sw.toString(); }

	  public static String getEvtTime()
	  {
	    Calendar now = Calendar.getInstance();
	    SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    String evt_timestamp = tempDate.format(now.getTime());
	    return evt_timestamp;
	  }

	  public static Timestamp getCurrentTimestamp() {
	    Calendar now = Calendar.getInstance();
	    SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
	    String evt_timestamp = tempDate.format(now.getTime());
	    Timestamp timestatmp = null;
	    try {
	      timestatmp = Timestamp.valueOf(evt_timestamp);
	    } catch (Exception ex) {
	      ex.printStackTrace();
	    }
	    return timestatmp;
	  }

	  public static String getEvtTimeforVer() {
	    Calendar now = Calendar.getInstance();
	    SimpleDateFormat tempDate = new SimpleDateFormat("yyyyMMdd");
	    String evt_timestamp = tempDate.format(now.getTime());
	    return evt_timestamp;
	  }

	  public static String getRvTime() {
	    Calendar now = Calendar.getInstance();
	    SimpleDateFormat tempDate = new SimpleDateFormat("yyyyMMddHHmmss");
	    String evt_timestamp = tempDate.format(now.getTime());
	    return evt_timestamp;
	  }

	  public static String getMillTimeStr() {
	    Calendar now = Calendar.getInstance();

	    SimpleDateFormat tempDate = new SimpleDateFormat(strMySQLTimeFormat);
	    String evt_timestamp = tempDate.format(now.getTime());
	    return evt_timestamp;
	  }

	  public static Date getMillTime() {
	    return String2Date(getMillTimeStr());
	  }

	  public static String formatEvtTime(Calendar calendar) {
	    SimpleDateFormat tempDate = new SimpleDateFormat(strMySQLTimeFormat);
	    String evt_timestamp = tempDate.format(calendar.getTime());
	    return evt_timestamp;
	  }

	  public static String formatRvTime(Calendar calendar) {
	    SimpleDateFormat tempDate = new SimpleDateFormat("yyyyMMddHHmmss");
	    String evt_timestamp = tempDate.format(calendar.getTime());
	    return evt_timestamp;
	  }

	  public static Date String2Date(String dateString) {
	    Date date = new Date();
	    try
	    {
	      SimpleDateFormat sdf = new SimpleDateFormat(strMySQLTimeFormat);
	      date = sdf.parse(dateString);
	    } catch (ParseException e) {
	      System.out.println(e.getMessage());
	    }
	    return date;
	  }

	  public static Date String2Time(String timeString) {
	    Date date = null;
	    try {
	      SimpleDateFormat sdf = new SimpleDateFormat("HH.mm.ss");
	      date = sdf.parse(timeString);
	    } catch (ParseException e) {
	      System.out.println(e.getMessage());
	    }
	    return date;
	  }

	  public static Timestamp String2Timestamp(String timeString) {
	    Timestamp timestatmp = null;
	    try {
	      timestatmp = Timestamp.valueOf(timeString);
	    } catch (Exception ex) {
	      ex.printStackTrace();
	    }
	    return timestatmp;
	  }

	  public static long getDiffMin(String startTime, String endTime)
	  {
	    long diffMin = 0L;
	    long nm = 60000L;
	    SimpleDateFormat sd = new SimpleDateFormat(strMySQLTimeFormat);
	    try
	    {
	      long diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
	      diffMin = diff / nm;
	    } catch (ParseException e) {
	      e.printStackTrace();
	    }
	    return diffMin;
	  }

	  public static long getDiffMin(Timestamp startTime, Timestamp endTime)
	  {
	    long diffMin = 0L;
	    long nm = 60000L;

	    long diff = endTime.getTime() - startTime.getTime();
	    diffMin = diff / nm;

	    return diffMin;
	  }

	  public static boolean isSpaceCheck(String str)
	  {
	    return (str == null) || (str.length() <= 0) || ("".equals(str));
	  }

	  public static Double getDoubleTime()
	  {
	    long now = System.currentTimeMillis();

	    Calendar calendar = Calendar.getInstance();
	    calendar.setTimeInMillis(now);

	    int year = calendar.get(1);
	    int month = calendar.get(2) + 1;
	    int day = calendar.get(5);
	    int hour = calendar.get(11);
	    int minute = calendar.get(12);
	    int second = calendar.get(13);
	    int millisecond = calendar.get(14);

	    Double days = Double.valueOf("0");
	    for (int i = 1900; i < year; i++) {
	      days = Double.valueOf(days.doubleValue() + getDaysByYear(i));
	    }

	    int[] days_each_month = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
	    if (isLeepYear(year)) {
	      days_each_month[1] = 29;
	    }

	    for (int i = 0; i < month - 1; i++) {
	      days = Double.valueOf(days.doubleValue() + days_each_month[i]);
	    }

	    days = Double.valueOf(days.doubleValue() + day + 1.0D);

	    double seconds = hour * 3600 + minute * 60 + second;
	    double millSeconds = millisecond + seconds * 1000.0D;

	    Double d = Double.valueOf(millSeconds / 86400000.0D);
	    return Double.valueOf(days.doubleValue() + d.doubleValue());
	  }
	  public static Double getMaxDoubleTime() {
	    double days = 0.0D;
	    for (int i = 1900; i < 2037; i++) {
	      days += getDaysByYear(i);
	    }

	    int[] days_each_month = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 
	      31, 30, 31 };
	    if (isLeepYear(2037)) {
	      days_each_month[1] = 29;
	    }

	    for (int i = 0; i < 0; i++) {
	      days += days_each_month[i];
	    }

	    days += 1.0D;

	    double d = 0.0D;
	    return Double.valueOf(days);
	  }

	  private static int getDaysByYear(int year) {
	    if (isLeepYear(year)) {
	      return 366;
	    }
	    return 365;
	  }

	  private static boolean isLeepYear(int year)
	  {
	    return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
	  }

	  public static String comInt2String(int value, int length)
	  {
	    String s = String.valueOf(value);
	    if (s.length() > length)
	      throw new RuntimeException("length is too short.");
	    if (s.length() == length) {
	      return s;
	    }
	    char[] cc = new char[length];
	    int i = 0;
	    for (; i < length - s.length(); i++) {
	      cc[i] = '0';
	    }
	    for (; i < length; i++)
	    {
	      cc[i] = s.charAt(length - i - 1);
	    }
	    return new String(cc);
	  }

	  public static int checkTimeMaxVal(int time, String type) {
	    if (("MON".equals(type)) && (time > 12)) {
	      return 0;
	    }
	    if (("DAY".equals(type)) && (time > 31)) {
	      return 0;
	    }
	    if ((("HOUR".equals(type)) || ("MINUTE".equals(type)) || ("SECOND".equals(type))) && 
	      (time >= 60)) {
	      return 0;
	    }

	    return time;
	  }

	  public static String getTimestampByDblTime(double dTime)
	  {
	    int alldays = (int)dTime; int year = 0; int mon = 0; int day = 0; int passDays = 0;
	    double allFloatPartDay = dTime - alldays;

	    StringBuffer timeStamp = new StringBuffer();
	    timeStamp.setLength(0);

	    year = (int)(dTime / 365.25D + 1900.0D);

	    for (int i = 1900; i < year; i++) {
	      passDays += getDaysByYear(i);
	    }
	    int[] days_each_month = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
	    if (isLeepYear(year)) {
	      days_each_month[1] = 29;
	    }

	    int days = 0;
	    int remainDays = alldays - passDays - 1;
	    for (int i = 0; i < 12; i++) {
	      if (days + days_each_month[i] >= remainDays) {
	        mon = i + 1;
	        day = remainDays - days;
	        break;
	      }
	      days += days_each_month[i];
	    }

	    int hour = (int)(24.0D * allFloatPartDay);
	    int minute = (int)(1440.0D * allFloatPartDay - 60 * hour);
	    int second = (int)(86400.0D * allFloatPartDay - 60 * minute - 3600 * hour);

	    timeStamp.append(year).append("-").append(comInt2String(checkTimeMaxVal(mon, "MON"), 2))
	      .append("-").append(comInt2String(checkTimeMaxVal(day, "DAY"), 2)).append(" ")
	      .append(comInt2String(checkTimeMaxVal(hour, "HOUR"), 2)).append(":")
	      .append(comInt2String(checkTimeMaxVal(minute, "MINUTE"), 2)).append(":")
	      .append(comInt2String(checkTimeMaxVal(second, "SECOND"), 2));
	    return timeStamp.toString();
	  }

	  public static void main(String[] args)
	  {
//	    double dTime = getDoubleTime().doubleValue();
//	    System.out.println("doubleTime:" + dTime);

	    String timeStamp = getTimestampByDblTime(41983.65742333333);
	    System.out.println(timeStamp);
	  }
}